package com.brradish.android.pocketmoney

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Environment
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.widget.Button
import android.widget.Toast
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.JsonNodeFactory
import java.io.File


class MainActivity : ActivityCompat.OnRequestPermissionsResultCallback, AppCompatActivity() {

    private val dataList: MutableList<JsonNode> = ArrayList()
    private val mapper = ObjectMapper()
    private val TAG="test"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val btn_click_me = findViewById<Button>(R.id.button_add)
        btn_click_me.setOnClickListener({
            addOne()
            writeToFile(getFile())
            Log.d(TAG,"add one done")
        }
        )

        if (testPrimmison()) {
            try {
                readFromFile(getFile())
            } catch (e: Exception) {
                showMsg(e.toString())
            }
        }
    }

    private fun writeToFile(file: File) {
        file.printWriter().use { out ->
            dataList.forEach {
                out.println(it.toString())
            }
        }
    }

    private fun addOne() {
        val node = JsonNodeFactory.instance.objectNode()
        node.put("val", 10)
        this.dataList.add(node);
    }

    private fun showMsg(msg: String) {
        Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show()
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        if (requestCode == 0) {
            if (grantResults.size == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                try {
                    readFromFile(getFile())
                } catch (e: Exception) {
                    showMsg(e.toString())
                }
            } else {
                android.os.Process.killProcess(android.os.Process.myPid())
                System.exit(1)
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        }
    }

    private fun testPrimmison(): Boolean {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            Log.d("test", "permission not allow")


            ActivityCompat.requestPermissions(this,
                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                    0)
            return false
        }
        return true

    }

    private fun readFromFile(file: File) {

        dataList.clear()
        val lines: List<String> = file.readLines()
        for (line in lines) {
            Log.v("test", line)
            try {
                val node = mapper.readTree(line)
                dataList.add(node)
            } catch (e: Exception) {
                Log.e("test", "string err: $line")
            }
        }
        Log.d(TAG,"read  done  $dataList")
    }

    private fun getFile(): File {
        val state = Environment.getExternalStorageState()
        if (Environment.MEDIA_MOUNTED != state) {
            throw Exception("can't write")
        }

        val sdcard = Environment.getExternalStorageDirectory()
        //val sdcard = getExternalFilesDir(null)

        val dir = File(sdcard, "PocketMoney")
        if (!dir.exists() && !dir.mkdirs()) {
            throw Exception("mkdirs error $dir")
        }
        val file = File(dir, "data.json")
        if (!file.exists()) {
            file.createNewFile()
        }
        return file
    }
//
}
